package com.app.activitys.adapters;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.ByteArrayBuffer;

import com.app.activitys.ActivityMenu;
import com.app.activitys.ActivityProblemaInternet;
import com.app.activitys.Faixas;
import com.app.entidades.Bandas;
import com.app.entidades.Musicas;
import com.app.webservice.ListaMusicas;
import com.app.webservice.MusicaRest;
import com.example.applucianokikao.R;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.provider.MediaStore.Images.Media;
import android.content.ContentValues;

public class AdapterBandas extends BaseAdapter{

	private Context contexto;
	private List<Bandas> bandas;
	private ImageButton button_image;
	private Handler handler = new Handler();
	
	public AdapterBandas(Context context, List objects) {
		
		
		this.bandas = objects;
		
		this.contexto = context;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return bandas.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return bandas.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		// TODO Auto-generated method stub
		View v = arg1;
		
		final Bandas banda = bandas.get(arg0);
		// only inflate the view if it's null
		if (v == null) {
		    LayoutInflater vi
	                 = (LayoutInflater)contexto.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		    v = vi.inflate(R.layout.adapter_bandas_view,null);
		}
		
		button_image = (ImageButton) v.findViewById(R.id.button_banda);
		TextView nome = (TextView) v.findViewById(R.id.txt_nome_banda);
		
		
		Bitmap m = buscaImagem(nomeImagem(banda.getCapa()));
		
		if(m==null){
			// baixa a imagem e salva no celular
			baixaImagem(banda.getCapa());
			button_image.setImageResource(R.drawable.foto_banda_padrao);
			//ai buscamos de novo
		}else{
			button_image.setImageBitmap(m);
		}
		
		button_image.setAdjustViewBounds(true);
		nome.setText(banda.getTitulo());
		
		button_image.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final String pastaBanda = banda.getPasta();
				
				AsyncTask<Void, Void,List<Musicas>> task = new AsyncTask<Void,Void,List<Musicas>>(){

					@Override
					protected List<Musicas> doInBackground(Void... params) {
						MusicaRest rest = new MusicaRest();
						List<Musicas> musicas = new ArrayList<Musicas>();
						
						try {
							musicas = rest.getListaMusicas(pastaBanda);
						}catch (Exception e) {
							Intent intent = new Intent(contexto, ActivityProblemaInternet.class);
							contexto.startActivity(intent);
							this.cancel(true);
						}
						return musicas;
					}
					
					@Override
			        protected void onPostExecute(List<Musicas> result) {
						Toast.makeText(contexto, "Listando Musicas", Toast.LENGTH_SHORT).show();
						Bundle bundle = new Bundle();
						bundle.putSerializable("musicas", (Serializable)result);
						Intent intent = new Intent(contexto, Faixas.class);
						intent.putExtra("mus", bundle);
						contexto.startActivity(intent);
					}
				
				};
				task.execute();
			}
			
		});
		
		
		return (v);
	}
	
	private void baixaImagem(final String url) {
      System.out.println("baixando");
		new Thread(new Runnable() {	
			@Override
			public void run() {
			        try {
			        	URL aURL = new URL(url);
					    URLConnection conn = aURL.openConnection();
					    conn.connect();
					        
					    
					    InputStream is = conn.getInputStream();
					    final BufferedInputStream bis = new BufferedInputStream(is);
					    
					    String nome = nomeImagem(url);
					    
					    ContentValues values = new ContentValues(3);
					    values.put(Media.DISPLAY_NAME, nome);
					    values.put(Media.DESCRIPTION, "Imagem bandas");
					    values.put(Media.MIME_TYPE, "image/jpeg");
					    
					    File file = new File(Environment.getExternalStorageDirectory()+"/Kikao/");

					    
					    FileOutputStream fos = new FileOutputStream(file+"/"+nome);
					    
					    // fos= (FileOutputStream) contexto.getContentResolver().openOutputStream(Uri);
					    fos.write(getBytes(bis));
					    fos.flush();
					    fos.close();
					    System.out.println("Baixou e Salvou");
					    bis.close();
					    is.close();
				   } catch (IOException e) {
					      Log.e("ImagemButton", "Error getting bitmap", e);
				   }
			}
    	}).start();
    }
	
	private Bitmap buscaImagem(String nomeImagem){
		Bitmap bmp=null;
			
		    File file = new File(Environment.getExternalStorageDirectory()+"/Kikao/"+nomeImagem);
		    if(file.exists()){
		    	System.out.println("existe");
		    	bmp = BitmapFactory.decodeFile(file.getPath());
		    }else{
		    	System.out.println("não existe");
		    }
			return bmp;
		
	}
	
	private String nomeImagem(String link){
		String[] valores = link.split("/");
		return valores[valores.length-1];
	}
	
	
	public byte[] getBytes(BufferedInputStream bis){
		ByteArrayBuffer baf = new ByteArrayBuffer(50);

		int count = 0;

		try {
			while((count = bis.read()) != -1){
				baf.append((byte) count);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return baf.toByteArray();
	}
	
	private void gerarToast(CharSequence message) {
		Toast.makeText(contexto, message,Toast.LENGTH_SHORT).show();
	}
}
